import React, { useEffect, useRef, useState } from "react";
import { Form, Row, Col, Button, Space, Input, message, Spin } from "antd";
import UploadImgX from "../uploadx";
import { changeDrawerState } from "@/store/modules/themeStore";
import { useAppDispatch, useAppSelector } from "@/store/hook.ts";
import { uploadSddInfo, updateSddInfo } from "@/api/api_ssd";
import { changeupdateState } from "@/store/modules/assStore";
const type = "SSD";

interface ChildMethods {
  handleUpload: () => void;
}

function SsdItem({ assInfo }) {
  const isAdd = useAppSelector((state) => state.ass.isAdd);
  const update = useAppSelector((state) => state.ass.update);
  const [form] = Form.useForm();

  useEffect(() => {
    if (!isAdd) {
      const {
        manufacturers,
        capacity,
        interfaceType,
        r_speed,
        w_speed,
        price,
        score,
      } = assInfo;
      const data = {
        ssdManufacturer: manufacturers,
        ssdCapacity: capacity,
        ssdInterfaceType: interfaceType,
        ssdRSpeed: r_speed,
        ssdWSpeed: w_speed,
        price,
        score,
      };
      form.setFieldsValue(data);
    } else {
      form.resetFields();
    }
  }, [isAdd, assInfo, form]);

  //SSD TSX
  const SSD = {
    MANUFACTURERS: (
      <Form.Item
        name="ssdManufacturer"
        label="SSD厂商"
        rules={[{ required: true, message: "Please input ssdManufacturer!" }]}
      >
        <Input />
      </Form.Item>
    ),
    CAPACITY: (
      <Form.Item
        name="ssdCapacity"
        label="SSD容量"
        rules={[{ required: true, message: "Please input ssdCapacity!" }]}
      >
        <Input suffix="TB" />
      </Form.Item>
    ),
    INTERFACE_TYPE: (
      <Form.Item
        name="ssdInterfaceType"
        label="接口类型"
        rules={[{ required: true, message: "Please input ssdInterfaceType!" }]}
      >
        <Input />
      </Form.Item>
    ),
    R_SPEED: (
      <Form.Item
        name="ssdRSpeed"
        label="读取速度"
        rules={[{ required: true, message: "Please input ssdRSpeed!" }]}
      >
        <Input suffix="MB/s" />
      </Form.Item>
    ),
    W_SPEED: (
      <Form.Item
        name="ssdWSpeed"
        label="写入速度"
        rules={[{ required: true, message: "Please input ssdWSpeed!" }]}
      >
        <Input suffix="MB/s" />
      </Form.Item>
    ),
    PRICE: (
      <Form.Item name="price" label="市场估价" rules={[{ required: true }]}>
        <Input prefix="￥" suffix="RMB" />
      </Form.Item>
    ),
    SCORE: (
      <Form.Item
        name="score"
        label="性能评分"
        rules={[{ required: true, message: "Please input score!" }]}
      >
        <Input />
      </Form.Item>
    ),
  };

  const childRef = useRef<ChildMethods>(null); // 创建一个 ref 来引用子组件

  const [spinning, setSpinning] = useState(false);

  const dispatch = useAppDispatch();

  // 表单验证
  const validateMessages = {
    required: "${label} is required!",
    types: {
      email: "${label} is not a valid email!",
      number: "${label} is not a valid number!",
    },
    number: {
      range: "${label} must be between ${min} and ${max}",
    },
  };

  // 表单提交
  const onFinish = async (values: any) => {
    setSpinning(true);
    const img_url_arr = await handleImageUpload();
    handleFormSubmit(values, img_url_arr as string[]);
  };

  //弹窗的状态控制
  const onClose = () => {
    dispatch(changeDrawerState(false));
  };

  //上传图片
  const handleImageUpload = async () => {
    if (childRef.current) {
      const result = childRef.current.handleUpload();
      return result;
    } else {
      return [];
    }
  };

  //添加Center信息
  const handleFormSubmit = async (values: any, img_url_arr: string[]) => {
    try {
      const info = {
        manufacturers: values.ssdManufacturer,
        capacity: values.ssdCapacity,
        interfaceType: values.ssdInterfaceType,
        r_speed: values.ssdRSpeed,
        w_speed: values.ssdWSpeed,
        price: parseFloat(values.price),
        img_url_arr,
        score: parseFloat(values.score),
      };
      if (!isAdd) {
        await updateSddInfo(assInfo._id, info);
        message.success("更新成功");
      } else {
        await uploadSddInfo(info);
        message.success("添加成功");
      }
      setSpinning(false);
      form.resetFields();
      dispatch(changeupdateState(!update));
      dispatch(changeDrawerState(false));
    } catch (error) {
      console.error(error);
      message.error("添加失败，请重试");
    }
  };

  return (
    <>
      <Spin spinning={spinning} fullscreen />
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        validateMessages={validateMessages}
      >
        {/* 详情图 */}

        <Form.Item>
          <div style={{ fontWeight: "bold", marginBottom: 10 }}>详情图</div>
          <UploadImgX ref={childRef} type={type} />
        </Form.Item>

        {/* GPU主要信息 */}
        <Row gutter={16}>
          <Col span={12}>{SSD.MANUFACTURERS}</Col>
          <Col span={12}>{SSD.CAPACITY}</Col>
          <Col span={12}>{SSD.INTERFACE_TYPE}</Col>
          <Col span={12}>{SSD.R_SPEED}</Col>
          <Col span={12}>{SSD.W_SPEED}</Col>
          <Col span={12}>{SSD.SCORE}</Col>
          <Col span={12}>{SSD.PRICE}</Col>
        </Row>
        <Form.Item>
          <Space size="large">
            <Button type="primary" danger htmlType="reset" onClick={onClose}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              添加
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

export default SsdItem;
